package com.efounder.frame.xmlparse;

import android.text.TextUtils;
import android.util.Log;

import com.core.xml.StubObject;
import com.efounder.constant.EnvironmentVariable;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Created by XinQing on 2016/8/29.
 */

public class EFAppAccountRegistry {
    private static final String KEY_XML_PATH = "key_xml_path";
    private static final String ELEMENT_NAME = "_elementName";
    /**父id**/
    public static final String ATTR_PARENT_ID = "parentID";
    public static final String NODE_TEXT = "_text";
    public static final String ATTR_PERMISSION = "permission";
    public static final String ELE_MENU_ROOT = "menuRoot";

    /**key:元素名  value:下级节点List**/
    private static Map<String, List<StubObject>> hierarchyMap = new HashMap<>();
    private static Map<String, List<StubObject>> tempMap = new HashMap<>();
    /**key:id  value:元素属性**/
    private static Map<String, StubObject> elementMap = new HashMap<>();
    /**
     功能权限列表
     TGAPP01 需求计划
     TGAPP02 发货签认
     没有权限管理时，permissionList==null；
     有权限管理时：若用户完全没有权限permissionList.size() == 0;
     **/
    private static List<String> permissionList;
//    private static List<String> permissionList = new ArrayList<>();

//    static {
//        permissionList = new ArrayList<>();
//        permissionList.add("TGAPP01");
////        permissionList.add("TGAPP02");
//    }

    private EFAppAccountRegistry() {
        super();
    }

    public static void init(String xmlPath) {
        //FIXME 如果更换了xml文件路径,重新注册  EFAppAccountUtils.getAppAccountRootPath()？
//        if (!xmlPath.equals(EnvironmentVariable.getProperty(KEY_XML_PATH))){
//        }
        clearRegister();
        EnvironmentVariable.setProperty(KEY_XML_PATH,xmlPath);
        parseXml(xmlPath);
    }

    public static void clearRegister(){
        hierarchyMap.clear();
        elementMap.clear();
        //FIXME
//        EnvironmentVariable.setProperty(KEY_XML_PATH,"");
    }

    /**
     * @param xmlPath
     * @return
     */
    private static void parseXml(String xmlPath) {
        if(TextUtils.isEmpty(xmlPath)){
            //FIXBUG 某些应用号文件可能没有资源配置文件,此处可能为空
            return ;
        }

        File xmlFile = new File(xmlPath);
        if (xmlFile.exists()) {
            try {
                //首先得到：得到 DOM 解析器的工厂实例
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(new FileInputStream(xmlFile));
                Element rootElement = document.getDocumentElement();
                recurParseElement(rootElement);
                //TODO 根据权限过滤 hierarchyMap
                if (permissionList == null ) return;
                if (permissionList.size()==1 && permissionList.get(0).equals("null")) return;
//                filterHierarchyMapByPermission(ELE_MENU_ROOT);
                filterHierarchyMapByPermission();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /***
     * 根据权限过滤 hierarchyMap
     */
    private static void filterHierarchyMapByPermission(String key){
        List<StubObject> menuRootList = hierarchyMap.get(key);
        if (menuRootList == null) return ;
        Iterator<StubObject> iterator = menuRootList.iterator();
        while (iterator.hasNext()) {
            StubObject stub = iterator.next();
            String permissionConfig = stub.getString(ATTR_PERMISSION,null);
            if (permissionConfig == null || permissionList.contains(permissionConfig)){//如果没有配置permission，默认显示
                filterHierarchyMapByPermission((String) stub.getID());
            }else{
                iterator.remove();
            }
        }
        if (menuRootList.size() == 0){
            hierarchyMap.remove(key);
            //删除上级List中的Stub
            StubObject currentStub = elementMap.get(key);
            List<StubObject> parentStubList = hierarchyMap.get(currentStub.getString(ATTR_PARENT_ID,null));
            parentStubList.remove(currentStub);

        }
    }

    /***
     * 根据权限过滤 hierarchyMap
     */
    private static void filterHierarchyMapByPermission(){
        tempMap.putAll(hierarchyMap);
        hierarchyMap.clear();

        //1.控制权限
        List<StubObject> childStubList = getChildStubList(tempMap.get(ELE_MENU_ROOT));
        hierarchyMap.put(ELE_MENU_ROOT,childStubList);

        //2.TODO 元素necessary="1" 都加上
        List<StubObject> stubList = tempMap.get("package");
        for (StubObject stub:stubList) {
            if ("1".equals(stub.getString("necessary","0"))){
                String elementName = stub.getString(ELEMENT_NAME,"");
                hierarchyMap.put(elementName,tempMap.get(elementName));
            }
        }

        Log.i("","");

    }

    private static List<StubObject> getChildStubList(List<StubObject> tempList){
        List<StubObject> stubList = new ArrayList<>();
        for (StubObject stub:tempList) {
            String permissionConfig = stub.getString(ATTR_PERMISSION,null);
            if (permissionConfig == null || permissionList.contains(permissionConfig)){//如果没有配置permission，默认显示
                //判断是否有孩子
                List<StubObject> childTempList = tempMap.get(stub.getID());
                if (childTempList == null){//没有子节点了，直接add
                    stubList.add(stub);
                }else{
                    List<StubObject> childStubList = getChildStubList(childTempList);
                    if (childStubList.size() > 0){//有子节点，add
                        stubList.add(stub);
                    }
                    hierarchyMap.put((String)stub.getID(),childStubList);
                }

            }
        }
        return stubList;
    }

    /***
     * 递归解析xml元素
     *
     * @param element
     */
    private static void recurParseElement(Element element) {
        //1.获取元素名,作为map的key
        String elementName = element.getNodeName();
        //2.获取子元素列表，放入list
        NodeList childNodeList = element.getChildNodes();
        List<StubObject> stubList = new ArrayList<>();
        for (int i = 0; i < childNodeList.getLength(); i++) {
            Node childNode = childNodeList.item(i);
            short nodeType = childNode.getNodeType();
            if (nodeType == Node.ELEMENT_NODE) {
                //3.获取子元素属性，放入stub中
                StubObject stub = new StubObject();
                //属性节点
                NamedNodeMap attrs = childNode.getAttributes();
                for (int j=0; j<attrs.getLength(); j++){
                    Node attr = attrs.item(j);
                    stub.setString(attr.getNodeName(),attr.getNodeValue());
                }
                //TODO 子节点元素名
                String childElementName = childNode.getNodeName();
                stub.setString(ELEMENT_NAME,childElementName);

                //text节点
                Node firstChildNode = childNode.getFirstChild();
                if (firstChildNode != null && firstChildNode.getNodeType() == Node.TEXT_NODE
                        && firstChildNode.getNodeValue() !=null && !"".equals(firstChildNode.getNodeValue().trim())){
                    stub.setString(NODE_TEXT,firstChildNode.getNodeValue().trim());
                }
                //放入parentID
                stub.setString(ATTR_PARENT_ID,elementName);
                //放入list
                stubList.add(stub);
                //2.如果有id属性，放入elementMap
                String id = stub.getString("id","");
                if (!id.equals("")){
                    elementMap.put(id,stub);
                }

                //开始递归
                if (childNode.hasChildNodes())
                    recurParseElement((Element) childNode);
            }
        }
        //放入map
        hierarchyMap.put(elementName,stubList);
    }

    public static StubObject getStubByID(String id){
        if (elementMap.size() == 0){
            parseXml(EnvironmentVariable.getProperty(KEY_XML_PATH));
        }
        return  elementMap.get(id);
    }

    public static List<StubObject> getStubListByElementName(String elementName){
        if (hierarchyMap.size() == 0){
            String property = EnvironmentVariable.getProperty(KEY_XML_PATH);
            parseXml(property);
        }
        return hierarchyMap.get(elementName);
    }

    public static List<String> getPermissionList() {
        return permissionList;
    }

    public static void setPermissionList(List<String> permissionList) {
        EFAppAccountRegistry.permissionList = permissionList;
    }
}
